/**
 * Created by Administrator on 2015/12/1.
 */
var express = require('express');
var router = express.Router();
var service = require('../service/service');


module.exports = router;

router.use(function(req,res,next){
    console.log('user is called');
    var url = req.path;
    var allowedUrls = ['/login','/register'];
    var allowed = false;
    if(!req.session.user){//没有登录的用户是可以访问login和register
        for(var i = 0;i<allowedUrls.length;i++){
            var r = new RegExp("^"+allowedUrls[i]+"$");
            if(r.test(url)){
                allowed = true;
                break;
            }
        }
    }else {
        allowed = true;
    }
    if(!allowed){
        res.redirect('/refuse.html');
    }else{
        next();
    }


});
router.post('/login',function(req,res,next){

    service.login(req.body,function(retMsg){//登录失败没有写
        console.log(retMsg);
        if(retMsg.state){
            req.session.user = retMsg.user;
            res.redirect('/');
        }else{
            //req.session.user = retMsg.user;
            //retMsg.sessionID = req.sessionID;
            res.render('user/login-state',retMsg);
        }

    });

});
router.post('/register',function(req,res,next){
    service.register(req.body,function(retMsg){
        console.log(retMsg);
        res.render('user/register-state',retMsg);
    })
});

router.get('/editform',function(req,res,next){
    var user = req.session.user;
    res.render('user/editform',user);
});

router.post('/edit',function(req,res,next){
    console.log(req.body);
    service.editUser(req.session.user._id,req.body,function(retMsg){
        if(retMsg.state){
            req.session.user = retMsg.user;
            res.redirect('/user/editform');
        }else {
            retMsg.title = '修改用户资料';
            res.render('user/update-error',retMsg);
        }
    })
});

router.get('/loginout',function(req,res,next){
    if(req.session.user){
        delete req.session.user;
        res.redirect('/');
    }
});

router.get('/editpassform',function(req,res,next){//密码修改

    res.render('user/editpassform');
});

router.post('/editpass',function(req,res,next){
    if(req.body.oldpassword !== req.session.user.password){
        var retMsg = {};
        retMsg.state = 0;
        retMsg.message = '旧密码输入错误';
        retMsg.title = '修改用户密码';
        res.render('user/update-error',retMsg);
    }

    if(req.session.user){
        service.editPassword(req.session.user._id,{password:req.body.password},function(retMsg){
            if(retMsg.state){
                res.redirect('/user/editpassform');
            }else{
                retMsg.title = '修改用户密码';
                res.render('user/update-error',retMsg);
            }
        })
    }
});